import subprocess
import sys


def upgrade_all_packages():
    # 调用 pip list --outdated 并捕获输出
    result = subprocess.run(
        [sys.executable, '-m', 'pip', 'list', '--outdated', '-i', 'https://pypi.tuna.tsinghua.edu.cn/simple'],
        stdout=subprocess.PIPE, text=True)
    outdated_lines = result.stdout.splitlines()[2:]  # 跳过表头
    outdated_packages = [line.split()[0] for line in outdated_lines]  # 假设第一列是包名

    for package in outdated_packages:
        try:
            print(f"更新 {package}...")
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', package, '-i',
                                   'https://pypi.tuna.tsinghua.edu.cn/simple'])
        except subprocess.CalledProcessError as e:
            print(f"升级失败 {package}: {e}")


if __name__ == "__main__":
    upgrade_all_packages()
